import axios from "axios";
// import { Message } from "element-ui";
import { navigate } from "svelte-routing";
import { toast } from "@zerodevx/svelte-toast";
import { user, token } from "../store";

// import router from "../router";
axios.defaults.withCredentials = true;

export const success = (m) =>
  toast.push(m, {
    theme: {
      "--toastBackground": "green",
      "--toastColor": "white",
      "--toastBarBackground": "olive",
    },
  });

const debug = true;
// 创建axios实例
const axiosInstance = axios.create({
  baseURL: process.env.VUE_APP_API_URL || "http://localhost:3000/api", // 后端API地址
  timeout: 5000,
});

// 请求拦截器：添加Token
axiosInstance.interceptors.request.use(
  (config) => {
    // 打印请求调试信息
    if (debug) {
      console.groupCollapsed(
        `[请求] ${config.method.toUpperCase()} ${config.url}`
      );
      console.log("请求地址:", config.baseURL + config.url);
      console.log("请求方法:", config.method.toUpperCase());
      console.log("请求参数:", config.params || config.data || "无");
      console.log("请求头:", config.headers);
      console.groupEnd();
    }

    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器：处理错误
axiosInstance.interceptors.response.use(
  (response) => {
    // 打印成功响应调试信息
    if (debug) {
      console.groupCollapsed(
        `[响应] ${response.config.method.toUpperCase()} ${
          response.config.url
        } (${response.status})`
      );
      console.log("响应状态:", response.status, response.statusText);
      console.log("响应数据:", response.data);
      console.log("响应时间:", new Date().toLocaleTimeString());
      console.groupEnd();
    }
    return response.data;
  },
  (error) => {
    console.log("error, ", error);
    // 未登录或Token过期
    if (error.response && error.response.status === 401) {
      // localStorage.removeItem("token");
      // localStorage.removeItem("user");
      user.set(null);
      token.set(null);
      // router.push("/auth/login");
      navigate("/login");
      // Message.error("登录已过期，请重新登录");
      toast.push("登录已过期，请重新登录");
    } else {
      //  element_ui__WEBPACK_IMPORTED_MODULE_2__.Message.error is not a function
      // Message.error(error.response?.data?.message || "操作失败");
      console.error("响应错误:", error);
      // Message.error(error.response?.data?.message || "操作失败");
      toast.push(error.response?.data?.message || "操作失败");
    }
    return Promise.reject(error.response.data);
  }
);

export default axiosInstance;
